package com.bdqn.maven.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.bdqn.maven.entity.User;
import com.bdqn.maven.service.UserService;
import com.github.pagehelper.PageInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public ModelAndView index() {
        try {
            User user = userService.findById(1);
            ModelAndView mv = new ModelAndView("user/index");
            mv.addObject("user", user);
            return mv;
        } catch (Exception e) {
            logger.error("获取首页用户信息失败", e);
            return new ModelAndView("error");
        }
    }

    @GetMapping("/getAllUsers")
    public ModelAndView getAllUsers(@RequestParam(defaultValue = "1") int pageNum,
                                    @RequestParam(defaultValue = "10") int pageSize) {
        try {
            PageInfo<User> pageInfo = userService.getAllUsersByPage(pageNum, pageSize);
            ModelAndView mv = new ModelAndView("user/allUsers");
            mv.addObject("pageInfo", pageInfo);
            return mv;
        } catch (Exception e) {
            logger.error("获取所有用户信息失败", e);
            return new ModelAndView("error");
        }
    }

    @GetMapping("/toUpdateUser")
    public ModelAndView toUpdateUser(@RequestParam("id") int id) {
        try {
            User user = userService.findById(id);
            ModelAndView mv = new ModelAndView("user/updateUser");
            mv.addObject("user", user);
            return mv;
        } catch (Exception e) {
            logger.error("跳转到修改用户页面失败，用户ID: {}", id, e);
            return new ModelAndView("error");
        }
    }

    @PostMapping("/updateUser")
    public String updateUser(User user, RedirectAttributes redirectAttributes) {
        try {
            User oldUser = userService.findById(user.getId());
            if (oldUser != null &&!oldUser.getUserpackage().equals(user.getUserpackage())) {
                double packagePrice = oldUser.getPackagePrice(user.getUserpackage());
                if (oldUser.getBalance() < packagePrice) {
                    redirectAttributes.addFlashAttribute("errorMessage", "余额不足");
                    return "redirect:/toUpdateUser?id=" + user.getId();
                } else {
                    user.setBalance(oldUser.getBalance() - packagePrice);
                    oldUser.addLog("更改套餐，扣除 " + packagePrice + " 元，当前余额: " + user.getBalance());
                    userService.saveUserLogs(oldUser);
                }
            }

            int result = userService.update(user);
            if (result > 0) {
                logger.info("用户ID: {} 信息更新成功", user.getId());
                return "redirect:/getAllUsers";
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "更新失败");
                logger.error("用户ID: {} 信息更新失败", user.getId());
                return "redirect:/toUpdateUser?id=" + user.getId();
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新过程中出现错误，请稍后重试");
            logger.error("用户ID: {} 信息更新出现异常", user.getId(), e);
            return "redirect:/toUpdateUser?id=" + user.getId();
        }
    }

    @GetMapping("/toAddUser")
    public ModelAndView toAddUser() {
        return new ModelAndView("user/addUser");
    }

    @PostMapping("/addUser")
    public String addUser(@RequestParam("username") String username, @RequestParam("password") String password,
                          @RequestParam("phone") String phone, @RequestParam("balance") Double balance,
                          RedirectAttributes redirectAttributes, @RequestParam("userpackage") Integer userpackage) {
        try {
            if (userService.isPhoneExists(phone)) {
                redirectAttributes.addFlashAttribute("phoneExists", true);
                return "redirect:/toAddUser";
            }
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setPhone(phone);
            user.setUserpackage(userpackage);
            user.setBalance(balance);
            user.setRole("user");
            int result = userService.add(user);
            if (result > 0) {
                redirectAttributes.addFlashAttribute("addUserSuccess", true);
                logger.info("用户: {} 注册成功", username);
                return "redirect:/getAllUsers";
            } else {
                redirectAttributes.addFlashAttribute("addUserSuccess", false);
                logger.error("用户: {} 注册失败", username);
                return "redirect:/toAddUser";
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("addUserSuccess", false);
            logger.error("用户: {} 注册出现异常", username, e);
            return "redirect:/toAddUser";
        }
    }

    @RequestMapping("/deleteMulti")
    public String deleteMulti(@RequestParam("id") int id, @RequestParam(defaultValue = "1") int pageNum) {
        try {
            userService.delete(id);
            logger.info("用户ID: {} 删除成功", id);
            return "redirect:/getAllUsers?pageNum=" + pageNum + "&pageSize=10";
        } catch (Exception e) {
            logger.error("用户ID: {} 删除失败", id, e);
            return "redirect:/getAllUsers?pageNum=" + pageNum + "&pageSize=10";
        }
    }

    @RequestMapping("/deleteMulti1")
    public String deleteMulti1(@RequestParam("id") int id) {
        try {
            userService.delete(id);
            logger.info("用户ID: {} 注销成功", id);
            return "redirect:/index";
        } catch (Exception e) {
            logger.error("用户ID: {} 注销失败", id, e);
            return "redirect:/index";
        }
    }

    @GetMapping("/toLogin")
    public ModelAndView toLogin() {
        return new ModelAndView("user/login");
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        HttpSession session) {
        try {
            User user = userService.findByUsernameAndPassword(username, password);
            if (user != null) {
                session.setAttribute("user", user);
                if ("admin".equals(user.getRole())) {
                    return "redirect:/getAllUsers";
                } else {
                    return "redirect:/userPage";
                }
            } else {
                logger.warn("用户: {} 登录失败，用户名或密码错误", username);
                return "redirect:/toLogin?error=1";
            }
        } catch (Exception e) {
            logger.error("用户: {} 登录出现异常", username, e);
            return "redirect:/toLogin?error=1";
        }
    }

    @GetMapping("/userPage")
    public ModelAndView userPage(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                user = userService.findById(user.getId());
            }
            ModelAndView mv = new ModelAndView("user/userPage");
            mv.addObject("user", user);
            return mv;
        } catch (Exception e) {
            logger.error("进入用户页面失败", e);
            return new ModelAndView("error");
        }
    }

    @GetMapping("/toRegister")
    public String toRegister(Model model) {
        return "user/register";
    }

    @PostMapping("/register")
    public String register(@RequestParam("username") String username, @RequestParam("password") String password,
                           @RequestParam("phone") String phone, @RequestParam("balance") Double balance,
                           RedirectAttributes redirectAttributes, @RequestParam("userpackage") Integer userpackage) {
        return addUser(username, password, phone, balance, redirectAttributes, userpackage);
    }

    @GetMapping("/toRecharge")
    public ModelAndView toRecharge(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                user = userService.findById(user.getId());
            }
            ModelAndView mv = new ModelAndView("user/recharge");
            mv.addObject("user", user);
            return mv;
        } catch (Exception e) {
            logger.error("跳转到充值页面失败", e);
            return new ModelAndView("error");
        }
    }

    @PostMapping("/recharge")
    public String recharge(@RequestParam("id") int id, @RequestParam("amount") double amount,
                           RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findById(id);
            if (user != null) {
                user.setBalance(user.getBalance() + amount);
                userService.update(user);
                redirectAttributes.addFlashAttribute("rechargeSuccess", true);
                user.addLog("充值 " + amount + " 元，当前余额: " + user.getBalance());
                userService.saveUserLogs(user);
                logger.info("用户ID: {} 充值 {} 元成功", id, amount);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("rechargeSuccess", false);
            logger.error("用户ID: {} 充值失败", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/toBills")
    public ModelAndView toBills(HttpSession session) {
        try {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                user = userService.findById(user.getId());
            }
            ModelAndView mv = new ModelAndView("user/bills");
            mv.addObject("user", user);
            return mv;
        } catch (Exception e) {
            logger.error("跳转到账单页面失败", e);
            return new ModelAndView("error");
        }
    }

    @GetMapping("/rechargeQQVip")
    public String rechargeQQVip(@RequestParam("id") int id, RedirectAttributes redirectAttributes) {
        try {
            if (userService.rechargeQQVip(id)) {
                redirectAttributes.addFlashAttribute("operationResult", "充值QQ会员成功，扣除10元话费");
                logger.info("用户ID: {} 充值QQ会员成功", id);
            } else {
                redirectAttributes.addFlashAttribute("operationResult", "余额不足，充值失败");
                logger.warn("用户ID: {} 充值QQ会员失败，余额不足", id);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("operationResult", "充值QQ会员出现异常，请稍后重试");
            logger.error("用户ID: {} 充值QQ会员出现异常", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/sendSms")
    public String sendSms(@RequestParam("id") int id, RedirectAttributes redirectAttributes) {
        try {
            if (userService.sendSms(id)) {
                redirectAttributes.addFlashAttribute("operationResult", "短信发送成功，扣除1条短信");
                logger.info("用户ID: {} 短信发送成功", id);
            } else {
                redirectAttributes.addFlashAttribute("operationResult", "短信不足或余额不足，请充值");
                logger.warn("用户ID: {} 短信发送失败，短信不足或余额不足", id);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("operationResult", "短信发送出现异常，请稍后重试");
            logger.error("用户ID: {} 短信发送出现异常", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/makeCall")
    public String makeCall(@RequestParam("id") int id, RedirectAttributes redirectAttributes) {
        try {
            if (userService.makeCall(id)) {
                redirectAttributes.addFlashAttribute("operationResult", "通话成功，扣除3元话费");
                logger.info("用户ID: {} 通话成功", id);
            } else {
                redirectAttributes.addFlashAttribute("operationResult", "余额不足，请充值");
                logger.warn("用户ID: {} 通话失败，余额不足", id);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("operationResult", "通话出现异常，请稍后重试");
            logger.error("用户ID: {} 通话出现异常", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/watchVideo")
    public String watchVideo(@RequestParam("id") int id, RedirectAttributes redirectAttributes) {
        try {
            if (userService.watchVideo(id)) {
                redirectAttributes.addFlashAttribute("operationResult", "观看视频成功，扣除2GB流量");
                logger.info("用户ID: {} 观看视频成功", id);
            } else {
                redirectAttributes.addFlashAttribute("operationResult", "流量不足或余额不足，请充值");
                logger.warn("用户ID: {} 观看视频失败，流量不足或余额不足", id);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("operationResult", "观看视频出现异常，请稍后重试");
            logger.error("用户ID: {} 观看视频出现异常", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/downloadLog")
    public void downloadLog(@RequestParam("id") int id, HttpServletResponse response) {
        try {
            String logDir = "D:/logs";
            File dir = new File(logDir);
            if (!dir.exists()) {
                if (dir.mkdirs()) {
                    logger.info("创建日志目录: {}", logDir);
                } else {
                    logger.error("无法创建日志目录: {}", logDir);
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "无法创建日志目录");
                    return;
                }
            }
            String filePath = logDir + File.separator + "user_" + id + "_log.txt";
            logger.info("准备保存日志到: {}", filePath);
            userService.saveLogToFile(id, filePath);

            File file = new File(filePath);
            if (file.exists() && file.length() > 0) {
                logger.info("文件存在，大小: {} 字节", file.length());
                response.setContentType("text/plain");
                response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
                try (FileInputStream fis = new FileInputStream(file);
                     OutputStream os = response.getOutputStream()) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        os.write(buffer, 0, length);
                    }
                    logger.info("文件下载成功");
                }
            } else {
                logger.error("文件不存在或为空: {}", filePath);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "日志文件为空");
            }
        } catch (Exception e) {
            logger.error("下载日志时出错: {}", e.getMessage(), e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载失败");
            } catch (IOException ex) {
                logger.error("发送错误响应时出错: {}", ex.getMessage(), ex);
            }
        }
    }

    @PostMapping("/changePackage")
    public String changePackage(@RequestParam("id") int id, @RequestParam("newPackage") int newPackage,
                                RedirectAttributes redirectAttributes) {
        try {
            if (userService.changePackage(id, newPackage)) {
                redirectAttributes.addFlashAttribute("operationResult", "套餐更改成功");
                logger.info("用户ID: {} 套餐更改成功", id);
            } else {
                redirectAttributes.addFlashAttribute("operationResult", "套餐更改失败");
                logger.warn("用户ID: {} 套餐更改失败", id);
            }
            return "redirect:/userPage";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("operationResult", "套餐更改出现异常，请稍后重试");
            logger.error("用户ID: {} 套餐更改出现异常", id, e);
            return "redirect:/userPage";
        }
    }

    @GetMapping("/toaaaaa")
    public ModelAndView toaaaaa() {
        return new ModelAndView("user/aaaaa");
    }

    @PostMapping("/aaaaa")
    public String aaaaa(@RequestParam("username") String username, @RequestParam("password") String password,
                        HttpSession session) {
        return login(username, password, session);
    }
}